import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource, MoreThan } from 'typeorm';
import { UserMembership } from './entities/user-membership.entity';
import { PurchaseMembershipDto } from './dto/purchase-membership.dto';
import { MembershipService } from '../membership/membership.service';
import { WalletService } from '../wallet/wallet.service';

/**
 * 用户会员服务
 */
@Injectable()
export class UserMembershipService {
  constructor(
    @InjectRepository(UserMembership)
    private readonly userMembershipRepository: Repository<UserMembership>,
    private readonly membershipService: MembershipService,
    private readonly walletService: WalletService,
    private readonly dataSource: DataSource,
  ) {}

  /**
   * 购买会员
   */
  async purchaseMembership(userId: number, purchaseDto: PurchaseMembershipDto): Promise<UserMembership> {
    const { packageId } = purchaseDto;
    
    // 获取套餐信息
    const membershipPackage = await this.membershipService.findOne(packageId);
    if (!membershipPackage.isActive) {
      throw new BadRequestException('该套餐已停售');
    }
    
    // 检查用户余额
    const wallet = await this.walletService.getWallet(userId);
    if (wallet.balance < membershipPackage.price) {
      throw new BadRequestException('余额不足');
    }
    
    return await this.dataSource.transaction(async (manager) => {
      // 扣除余额
      await this.walletService.deductBalance(userId, membershipPackage.price);
      
      // 计算会员时间
      const now = new Date();
      const currentMembership = await this.getCurrentMembership(userId);
      
      let startTime: Date;
      let endTime: Date;
      
      if (currentMembership && currentMembership.endTime > now) {
        // 如果当前会员未过期，从当前会员结束时间开始
        startTime = currentMembership.endTime;
      } else {
        // 如果没有会员或已过期，从现在开始
        startTime = now;
      }
      
      endTime = new Date(startTime.getTime() + membershipPackage.durationDays * 24 * 60 * 60 * 1000);
      
      // 创建会员记录
      const userMembership = this.userMembershipRepository.create({
        userId,
        packageId,
        startTime,
        endTime,
        paidAmount: membershipPackage.price,
        isActive: true,
      });
      
      return await manager.save(UserMembership, userMembership);
    });
  }

  /**
   * 获取用户当前会员信息
   */
  async getCurrentMembership(userId: number): Promise<UserMembership | null> {
    const now = new Date();
    
    return await this.userMembershipRepository.findOne({
      where: {
        userId,
        isActive: true,
        endTime: MoreThan(now),
      },
      relations: ['package'],
      order: { endTime: 'DESC' },
    });
  }

  /**
   * 检查用户是否为会员
   */
  async isUserMember(userId: number): Promise<boolean> {
    const membership = await this.getCurrentMembership(userId);
    return !!membership;
  }

  /**
   * 获取用户会员历史记录
   */
  async getUserMembershipHistory(userId: number, page = 1, limit = 10): Promise<{
    data: UserMembership[];
    total: number;
    page: number;
    limit: number;
  }> {
    const [data, total] = await this.userMembershipRepository.findAndCount({
      where: { userId },
      relations: ['package'],
      order: { createdAt: 'DESC' },
      skip: (page - 1) * limit,
      take: limit,
    });
    
    return { data, total, page, limit };
  }

  /**
   * 管理员获取所有用户会员状态
   */
  async getAllUserMemberships(page = 1, limit = 10): Promise<{
    data: UserMembership[];
    total: number;
    page: number;
    limit: number;
  }> {
    const [data, total] = await this.userMembershipRepository.findAndCount({
      relations: ['user', 'package'],
      order: { createdAt: 'DESC' },
      skip: (page - 1) * limit,
      take: limit,
    });
    
    return { data, total, page, limit };
  }

  /**
   * 手动设置用户会员（管理员功能）
   */
  async setUserMembership(
    userId: number,
    packageId: number,
    durationDays: number,
  ): Promise<UserMembership> {
    // 检查用户是否存在
    const wallet = await this.walletService.getWallet(userId);
    if (!wallet) {
      throw new NotFoundException(`用户 ID ${userId} 不存在`);
    }
    
    // 检查套餐是否存在
    const membershipPackage = await this.membershipService.findOne(packageId);
    
    const now = new Date();
    const currentMembership = await this.getCurrentMembership(userId);
    
    let startTime: Date;
    let endTime: Date;
    
    if (currentMembership && currentMembership.endTime > now) {
      // 如果当前会员未过期，从当前会员结束时间开始
      startTime = currentMembership.endTime;
    } else {
      // 如果没有会员或已过期，从现在开始
      startTime = now;
    }
    
    endTime = new Date(startTime.getTime() + durationDays * 24 * 60 * 60 * 1000);
    
    const userMembership = this.userMembershipRepository.create({
      userId,
      packageId,
      startTime,
      endTime,
      paidAmount: 0, // 管理员设置的会员不收费
      isActive: true,
    });
    
    return await this.userMembershipRepository.save(userMembership);
  }

  /**
   * 定时任务：检查并更新过期会员
   */
  async updateExpiredMemberships(): Promise<void> {
    const now = new Date();
    
    await this.userMembershipRepository.update(
      {
        isActive: true,
        endTime: MoreThan(now),
      },
      {
        isActive: false,
      },
    );
  }
}